package com.ihd.ihardware.view.scooter.view;

import android.arch.lifecycle.Observer;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.view.View;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.ihd.ihardware.R;
import com.ihd.ihardware.common.AppConstans;
import com.ihd.ihardware.common.utils.DataUtils;
import com.ihd.ihardware.common.widget.BtnRelativeLayout;
import com.ihd.ihardware.databinding.ActivityScBinding;
import com.ihd.ihardware.pojo.CurrStatus;
import com.ihd.ihardware.pojo.DeviceListRes;
import com.ihd.ihardware.view.scooter.viewModel.SCViewModel;
import com.inuker.bluetooth.library.connect.options.BleConnectOptions;
import com.inuker.bluetooth.library.connect.response.BleConnectResponse;
import com.inuker.bluetooth.library.model.BleGattProfile;
import com.inuker.bluetooth.library.search.SearchRequest;
import com.inuker.bluetooth.library.search.SearchResult;
import com.inuker.bluetooth.library.search.response.SearchResponse;
import com.jeremyliao.liveeventbus.LiveEventBus;

import java.text.DecimalFormat;
import java.util.List;

import cn.wowjoy.commonlibrary.base.BaseActivity;
import cn.wowjoy.commonlibrary.base.BaseConsumer;
import cn.wowjoy.commonlibrary.utils.BLEUtils;
import cn.wowjoy.commonlibrary.utils.CommonUtils;
import cn.wowjoy.commonlibrary.utils.DialogUtils;
import cn.wowjoy.commonlibrary.utils.SPUtils;
import cn.wowjoy.commonlibrary.utils.ToastUtils;
import cn.wowjoy.commonlibrary.widget.MDialog;

import static com.ihd.ihardware.common.AppConstans.Notify_Character_UUID;
import static com.ihd.ihardware.common.AppConstans.Notify_Service_UUID;
import static com.ihd.ihardware.common.AppConstans.Write_Character_UUID;
import static com.ihd.ihardware.common.AppConstans.Write_Service_UUID;
import static com.inuker.bluetooth.library.Constants.REQUEST_SUCCESS;

public class SCActivity extends BaseActivity<ActivityScBinding, SCViewModel> {
    private float rotate = -120.0f;
    private MDialog mPswDg;
    private MDialog mErrDg;
    private MDialog mDG;
    private DeviceListRes.DataBean.ListBean mBD;
    private CurrStatus mCurrStatus;
    private MDialog waitDialog;
    private BleConnectOptions options = new BleConnectOptions.Builder()
            .setConnectTimeout(3000)
            .setServiceDiscoverTimeout(3000)
            .build();

    @Override
    protected void init(Bundle savedInstanceState) {
        mImmersionBar.statusBarDarkFont(false).init();
        mBD = (DeviceListRes.DataBean.ListBean) getIntent().getSerializableExtra("sc");

        binding.title.setText(mBD.getNickname());
        binding.pin.setRotation(rotate);
        setRx(AppConstans.UNBIND, new BaseConsumer<DeviceListRes>() {
            @Override
            protected void onStart() {
            }

            @Override
            protected void onSuccess(DeviceListRes mLiveData) {
                SPUtils.putString(AppConstans.DEVICES, new Gson().toJson(mLiveData.getData().getList(), new TypeToken<List<DeviceListRes.DataBean.ListBean>>() {
                }.getType()));
            }

            @Override
            protected void onError(Throwable error) {
                ToastUtils.showShort(SCActivity.this, error.getMessage());
            }
        });

        searchNow();
        LiveEventBus.get()
                .with("onNotify", String.class)
                .observe(this, new Observer<String>() {
                    @Override
                    public void onChanged(@Nullable String s) {
//                        Log.e("onNotify onChanged", s);
                        if (s.contains(":")) {
                            BLEUtils.writePsw(s, "A50403", "0000", Write_Service_UUID, Write_Character_UUID);
                        } else {
                            if (s.startsWith("5A0F03")) {
                                mCurrStatus = DataUtils.parseStatus(s);

                                //灯
                                if (mCurrStatus.getLauto() == 1) {
                                    binding.light.setImageResource(R.drawable.bike_board_autolight);
                                    binding.lighthint.setImageResource(R.drawable.bike_borad_tipsauto);
                                } else {
                                    if (mCurrStatus.getLonoff() == 1) {
                                        binding.light.setImageResource(R.drawable.bike_board_light);
                                        binding.lighthint.setImageResource(R.drawable.bike_borad_tipsopen);
                                    } else {
                                        binding.light.setImageResource(R.drawable.bike_board_closelight);
                                        binding.lighthint.setImageResource(R.drawable.bike_borad_tipsclose);
                                    }
                                }

                                //电量
                                binding.battery.setProgress(mCurrStatus.getBattery() / 100f);
                                binding.batteryTxt.setText(mCurrStatus.getBattery() + "%");

//                                if (mCurrStatus.getLock() == 1)
//                                    binding.lock.setImageResource(R.drawable.fun_icon_lock);
//                                else
//                                    binding.lock.setImageResource(R.drawable.fun_icon_unlock);

                                //仪表盘
                                rotate = -120f + mCurrStatus.getSpeed() * 6;
                                binding.pin.setRotation(rotate);

                                //速度
                                if (SPUtils.getBoolean("km", true)) {
                                    binding.curSpeed.setText(new DecimalFormat("0.0").format(mCurrStatus.getSpeed()));
                                    binding.curSpeedHint.setText("km/h");
                                } else {
                                    binding.curSpeed.setText(new DecimalFormat("0.0").format(mCurrStatus.getSpeed() / 1.6));
                                    binding.curSpeedHint.setText("mile/h");
                                }

                                //距离
                                binding.distance.setText(String.valueOf(mCurrStatus.getCurrway()));

                                //时间
                                int ho = mCurrStatus.getRidetime() / 3600;
                                int mi = mCurrStatus.getRidetime() % 3600 / 60;
                                int se = mCurrStatus.getRidetime() % 3600 % 60;
                                binding.hh.setText(String.valueOf(ho));
                                binding.mm.setText(String.valueOf(mi));
                                binding.ss.setText(String.valueOf(se));

                                //档位
                                if (!binding.levelbtn.isTouching()) {
                                    if (mCurrStatus.getLevel() == 0 || mCurrStatus.getLevel() == 1) {
                                        binding.leveltxt.setText("Ⅰ");
                                        binding.levelbtn.setLevel(1);
                                    } else if (mCurrStatus.getLevel() == 2) {
                                        binding.leveltxt.setText("Ⅱ");
                                        binding.levelbtn.setLevel(2);
                                    } else {
                                        binding.leveltxt.setText("Ⅲ");
                                        binding.levelbtn.setLevel(3);
                                    }
                                }
                                BLEUtils.writePsw(mBD.getMac(), "A50403", "0000", Write_Service_UUID, Write_Character_UUID);
                            } else if (s.startsWith("5A0502")) {
                                new Handler().postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        if (s.startsWith("5A050201")) {
                                            if (mCurrStatus.getLock() == 1)
                                                ToastUtils.showShort(SCActivity.this, "锁车成功");
                                            else
                                                ToastUtils.showShort(SCActivity.this, "解锁成功");
                                        } else {
                                            if (mCurrStatus.getLock() == 1)
                                                ToastUtils.showShort(SCActivity.this, "锁车失败");
                                            else
                                                ToastUtils.showShort(SCActivity.this, "解锁失败");
                                        }
                                    }
                                }, 500);
                            }
                        }
                    }
                });

        binding.levelbtn.setOnCLickListener(new BtnRelativeLayout.OnCLickListener() {
            @Override
            public void onClick(int level) {
                if (level == 1) {
                    binding.leveltxt.setText("Ⅰ");
                    BLEUtils.writePsw(mBD.getMac(), "A5050501", "0000", Write_Service_UUID, Write_Character_UUID);
                } else if (level == 2) {
                    binding.leveltxt.setText("Ⅱ");
                    BLEUtils.writePsw(mBD.getMac(), "A5050502", "0000", Write_Service_UUID, Write_Character_UUID);
                } else {
                    binding.leveltxt.setText("Ⅲ");
                    BLEUtils.writePsw(mBD.getMac(), "A5050503", "0000", Write_Service_UUID, Write_Character_UUID);
                }
            }
        });

        binding.light.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mCurrStatus.getLauto() == 1) {
                    BLEUtils.writePsw(mBD.getMac(), "A5050400", "0000", Write_Service_UUID, Write_Character_UUID);
                } else {
                    if (mCurrStatus.getLonoff() == 1) {
                        BLEUtils.writePsw(mBD.getMac(), "A5050402", "0000", Write_Service_UUID, Write_Character_UUID);
                    } else {
                        BLEUtils.writePsw(mBD.getMac(), "A5050401", "0000", Write_Service_UUID, Write_Character_UUID);
                    }
                }
            }
        });

        binding.lock.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mCurrStatus.getLock() == 1)
                    BLEUtils.writePsw(mBD.getMac(), "A5050200", "0000", Write_Service_UUID, Write_Character_UUID);
                else
                    BLEUtils.writePsw(mBD.getMac(), "A5050201", "0000", Write_Service_UUID, Write_Character_UUID);
            }
        });

        binding.check.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent mIntent = new Intent(SCActivity.this, SCExamActivity.class);
                mIntent.putExtra("sc", mBD);
                startActivity(mIntent);
            }
        });
        binding.back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        binding.me.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent mIntent = new Intent(SCActivity.this, SCMeActivity.class);
                mIntent.putExtra("sc", mBD);
                startActivity(mIntent);
            }
        });
        binding.map.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent mIntent = new Intent(SCActivity.this, SCMapActivity.class);
                startActivity(mIntent);
            }
        });

        binding.exit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDG = DialogUtils.alertDialog(SCActivity.this, MDialog.DG_TYPE.SCALERT, "是否断开蓝牙并退出", "取消", "确定", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mDG.cancel();
                    }
                }, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mDG.cancel();
                        finish();
                    }
                });
            }
        });
        binding.unbind.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDG = DialogUtils.alertDialog(SCActivity.this, MDialog.DG_TYPE.SCALERT, "解除绑定后将无法同步，您确定要解绑滑板车？", "我再想想", "确认解绑", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mDG.cancel();
                    }
                }, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mDG.cancel();
                        viewModel.unbind(mBD.getId());
                    }
                });
            }
        });
        setRx(AppConstans.UNBIND, new BaseConsumer<DeviceListRes>() {
            @Override
            protected void onStart() {
            }

            @Override
            protected void onSuccess(DeviceListRes mLiveData) {
                DialogUtils.successDialog(SCActivity.this, MDialog.DG_TYPE.SUCCESS, R.drawable.toasticon_suc, "解除成功");
                SPUtils.putString(AppConstans.DEVICES, new Gson().toJson(mLiveData.getData().getList(), new TypeToken<List<DeviceListRes.DataBean.ListBean>>() {
                }.getType()));
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        finish();
                    }
                }, 1100);
            }

            @Override
            protected void onError(Throwable error) {
            }
        });

        connect();
    }

    private void searchNow() {
        BLEUtils.getInstance().search(new SearchRequest.Builder().searchBluetoothLeDevice(86400000).build(), new SearchResponse() {
            @Override
            public void onSearchStarted() {
            }

            @Override
            public void onDeviceFounded(SearchResult device) {
            }

            @Override
            public void onSearchStopped() {
            }

            @Override
            public void onSearchCanceled() {
            }
        });
    }

    private void connect() {
        waitDialog = DialogUtils.waitingDialog(SCActivity.this);
        BLEUtils.getInstance().connect(mBD.getMac(), options, new BleConnectResponse() {
            @Override
            public void onResponse(int code, BleGattProfile data) {
                if (code == REQUEST_SUCCESS) {
                    BLEUtils.openNotify(mBD.getMac(), Notify_Service_UUID, Notify_Character_UUID);
                } else {
                    ToastUtils.showLong(SCActivity.this, getString(R.string.conn_fail));
                    BLEUtils.getInstance().disconnect(CommonUtils.stringToMac(mBD.getMac()));
                }
                DialogUtils.dismiss(SCActivity.this);
            }
        });
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_sc;
    }

    @Override
    protected Class getViewModelClass() {
        return SCViewModel.class;
    }

    @Override
    protected void onDestroy() {
        BLEUtils.closeNotify(mBD.getMac(), Notify_Service_UUID, Notify_Character_UUID);
        BLEUtils.getInstance().stopSearch();
        super.onDestroy();
    }
}
